<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class BrandController extends Controller
{
    /**
     * 获取品牌列表，分页形式
     * @param Request $request
     * @return array
     */
    public function all(Request $request)
    {
        $title = $request->get('title', '');
        $limit = $request->get('limit', config('common.pagination.limit'));

        $query = Brand::where('title', 'like', '%' . $title . '%');
        $items = $query->orderBy('order')
            ->paginate($limit);
        return jsonResponse(config('common.successCode'), $items);
    }

    public function create(Request $request)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $title = $request->get('title');
        $logo = $request->get('logo');
        $url = $request->get('url');
        $ifShow = $request->get('ifShow');
        $desc = $request->get('desc');

        $brand = new Brand();
        $brand['title'] = $title;
        $brand['logo'] = $logo;
        $brand['url'] = $url;
        $brand['if_show'] = $ifShow;
        $brand['desc'] = $desc;
        $brand->save();
        return jsonResponse();
    }

    public function update(Request $request, $id)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $title = $request->get('title');
        $logo = $request->get('logo');
        $url = $request->get('url');
        $ifShow = $request->get('ifShow');
        $desc = $request->get('desc');

        $brand = Brand::find($id);
        if (empty($brand)) {
            return jsonResponse(40000);
        }
        $brand['title'] = $title;
        $brand['logo'] = $logo;
        $brand['url'] = $url;
        $brand['if_show'] = $ifShow;
        $brand['desc'] = $desc;
        $brand->save();
        return jsonResponse();
    }

    public function destroy($id)
    {
        Brand::destroy($id);
        return jsonResponse();
    }

    private function validate($request)
    {
        return Validator::make($request->all(), [
            'title' => 'required',
            'logo' => 'required',
            'url' => 'required|url',
            'if_show' => Rule::in([0, 1]),
        ], [
            'title.required' => '名称不能为空',
            'logo.required' => 'Logo不能为空',
            'url.required' => '网址不能为空',
            'url.url' => '网址不合法',
            'if_show.in' => '是否显示的值不合法',
        ]);
    }
}
